import { computed, ref, type InjectionKey } from 'vue'
import { createInjectionState } from '@vueuse/core'
import type { TodoModel } from './todo.types'

let id = 1
export const useTodo = () => {
  const list = ref<TodoModel[]>([])

  const add = (title: string) => {
    list.value.push({
      id: id++,
      title,
      completed: false
    })
  }

  const remove = (id: number) => {
    list.value = list.value.filter((todo) => todo.id !== id)
  }

  const completeTotal = computed(() => {
    return list.value.filter((todo) => todo.completed).length
  })

  const total = computed(() => {
    return list.value.length
  })

  const clearCompleted = () => {
    list.value = list.value.filter((todo) => !todo.completed)
  }

  const toggleAll = (completed: boolean) => {
    list.value.forEach((todo) => {
      todo.completed = completed
    })
  }

  const clearAll = () => {
    list.value = []
  }

  return {
    list,
    add,
    remove,
    completeTotal,
    total,
    clearCompleted,
    toggleAll,
    clearAll
  }
}

export type TodoCtx = ReturnType<typeof useTodo>

export const TodoCtxKey: InjectionKey<TodoCtx> = Symbol('TodoCtx')

const [useProvideTodoCtx, useTodoCtx] = createInjectionState(
  () => {
    return useTodo()
  },
  {
    injectionKey: TodoCtxKey
  }
)

export { useProvideTodoCtx, useTodoCtx }
